import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Card, Steps, Form, Input, Button, Row, Col, Select, DatePicker, message, Divider } from 'antd';
import styled from 'styled-components';
import MainLayout from '../../components/Layout/MainLayout';
import { getHotelDetail, getHotelRooms } from '../../api/hotelApi';
import { createOrder } from '../../api/orderApi';
import { Hotel, Room } from '../../api/types';

const { Step } = Steps;
const { Option } = Select;

const PageContainer = styled.div`
  padding: 20px 0;
`;

const StepsContainer = styled.div`
  margin-bottom: 30px;
`;

const OrderSummary = styled.div`
  background-color: #f8f8f8;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
`;

const SummaryTitle = styled.h3`
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
`;

const SummaryItem = styled.div`
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
`;

const ItemLabel = styled.div`
  color: #666;
`;

const ItemValue = styled.div`
  font-weight: 500;
`;

const TotalPrice = styled.div`
  font-size: 18px;
  font-weight: 600;
  color: #ff4d4f;
  text-align: right;
  margin-top: 15px;
`;

const OrderPage: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [form] = Form.useForm();
  
  // 从URL中获取参数
  const queryParams = new URLSearchParams(location.search);
  const hotelId = queryParams.get('hotelId');
  const roomId = queryParams.get('roomId');
  
  const [currentStep, setCurrentStep] = useState(0);
  const [hotel, setHotel] = useState<Hotel | null>(null);
  const [room, setRoom] = useState<Room | null>(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [orderDetails, setOrderDetails] = useState({
    checkInDate: '',
    checkOutDate: '',
    nights: 1,
    guests: 1,
    name: '',
    phone: '',
    totalPrice: 0
  });
  
  // 获取酒店和房间信息
  useEffect(() => {
    const fetchData = async () => {
      if (!hotelId || !roomId) {
        message.error('缺少必要参数');
        navigate('/');
        return;
      }
      
      setLoading(true);
      try {
        // 并行请求酒店和房间数据
        const [hotelRes, roomsRes] = await Promise.all([
          getHotelDetail(hotelId),
          getHotelRooms(hotelId)
        ]);
        
        setHotel(hotelRes.data);
        
        // 从房间列表中找到对应的房间
        const selectedRoom = roomsRes.data.find(r => r.id === roomId);
        if (selectedRoom) {
          setRoom(selectedRoom);
          
          // 计算默认的价格
          const price = selectedRoom.discount 
            ? Math.floor(selectedRoom.price * selectedRoom.discount / 100) 
            : selectedRoom.price;
            
          setOrderDetails(prev => ({
            ...prev,
            totalPrice: price
          }));
        } else {
          message.error('未找到指定的房间');
          navigate(`/hotel/${hotelId}`);
        }
      } catch (error) {
        console.error('获取数据失败', error);
        message.error('数据加载失败，请重试');
      } finally {
        setLoading(false);
      }
    };
    
    fetchData();
  }, [hotelId, roomId, navigate]);
  
  // 处理日期变化
  const handleDateChange = (dates: any) => {
    if (dates && dates.length === 2 && room) {
      const checkInDate = dates[0].format('YYYY-MM-DD');
      const checkOutDate = dates[1].format('YYYY-MM-DD');
      
      // 计算住宿天数
      const nights = dates[1].diff(dates[0], 'days');
      
      // 计算总价
      const pricePerNight = room.discount 
        ? Math.floor(room.price * room.discount / 100) 
        : room.price;
      const totalPrice = pricePerNight * nights;
      
      setOrderDetails(prev => ({
        ...prev,
        checkInDate,
        checkOutDate,
        nights,
        totalPrice
      }));
    }
  };
  
  // 处理入住人数变化
  const handleGuestsChange = (value: number) => {
    setOrderDetails(prev => ({
      ...prev,
      guests: value
    }));
  };
  
  // 填写联系人信息完成
  const handleContactInfoComplete = (values: any) => {
    setOrderDetails(prev => ({
      ...prev,
      name: values.name,
      phone: values.phone
    }));
    
    setCurrentStep(1);
  };
  
  // 确认订单信息完成
  const handleConfirmOrder = () => {
    setCurrentStep(2);
  };
  
  // 提交订单
  const handleSubmitOrder = async () => {
    if (!hotel || !room) return;
    
    setSubmitting(true);
    try {
      const orderData = {
        hotelId: hotel.id,
        hotelName: hotel.name,
        roomId: room.id,
        roomName: room.name,
        checkInDate: orderDetails.checkInDate,
        checkOutDate: orderDetails.checkOutDate,
        nights: orderDetails.nights,
        guests: orderDetails.guests,
        guestName: orderDetails.name,
        contactPhone: orderDetails.phone,
        totalPrice: orderDetails.totalPrice
      };
      
      const response = await createOrder(orderData);
      
      message.success('订单提交成功');
      navigate(`/order/${response.data.orderId}`);
    } catch (error) {
      console.error('提交订单失败', error);
      message.error('订单提交失败，请重试');
    } finally {
      setSubmitting(false);
    }
  };
  
  // 渲染联系人信息表单
  const renderContactInfoForm = () => (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleContactInfoComplete}
      initialValues={{
        guests: 1
      }}
    >
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            name="dateRange"
            label="入住/离店日期"
            rules={[{ required: true, message: '请选择入住和离店日期' }]}
          >
            <DatePicker.RangePicker
              style={{ width: '100%' }}
              onChange={handleDateChange}
            />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="guests"
            label="入住人数"
            rules={[{ required: true, message: '请选择入住人数' }]}
          >
            <Select onChange={handleGuestsChange}>
              {[1, 2, 3, 4].map(num => (
                <Option key={num} value={num}>{num}人</Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
      </Row>
      
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            name="name"
            label="入住人姓名"
            rules={[{ required: true, message: '请输入入住人姓名' }]}
          >
            <Input placeholder="请输入真实姓名" />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="phone"
            label="联系电话"
            rules={[
              { required: true, message: '请输入联系电话' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
            ]}
          >
            <Input placeholder="请输入手机号码" />
          </Form.Item>
        </Col>
      </Row>
      
      <Form.Item>
        <Button type="primary" htmlType="submit">
          下一步
        </Button>
      </Form.Item>
    </Form>
  );
  
  // 渲染订单确认信息
  const renderOrderConfirmation = () => (
    <div>
      <OrderSummary>
        <SummaryTitle>预订信息</SummaryTitle>
        
        <SummaryItem>
          <ItemLabel>酒店名称</ItemLabel>
          <ItemValue>{hotel?.name}</ItemValue>
        </SummaryItem>
        
        <SummaryItem>
          <ItemLabel>房型</ItemLabel>
          <ItemValue>{room?.name}</ItemValue>
        </SummaryItem>
        
        <SummaryItem>
          <ItemLabel>入住日期</ItemLabel>
          <ItemValue>{orderDetails.checkInDate}</ItemValue>
        </SummaryItem>
        
        <SummaryItem>
          <ItemLabel>离店日期</ItemLabel>
          <ItemValue>{orderDetails.checkOutDate}</ItemValue>
        </SummaryItem>
        
        <SummaryItem>
          <ItemLabel>住宿天数</ItemLabel>
          <ItemValue>{orderDetails.nights}晚</ItemValue>
        </SummaryItem>
        
        <SummaryItem>
          <ItemLabel>入住人数</ItemLabel>
          <ItemValue>{orderDetails.guests}人</ItemValue>
        </SummaryItem>
        
        <Divider style={{ margin: '15px 0' }} />
        
        <SummaryTitle>入住人信息</SummaryTitle>
        
        <SummaryItem>
          <ItemLabel>姓名</ItemLabel>
          <ItemValue>{orderDetails.name}</ItemValue>
        </SummaryItem>
        
        <SummaryItem>
          <ItemLabel>联系电话</ItemLabel>
          <ItemValue>{orderDetails.phone}</ItemValue>
        </SummaryItem>
        
        <Divider style={{ margin: '15px 0' }} />
        
        <TotalPrice>总价: ¥{orderDetails.totalPrice}</TotalPrice>
      </OrderSummary>
      
      <div>
        <Button onClick={() => setCurrentStep(0)} style={{ marginRight: 16 }}>
          返回修改
        </Button>
        <Button type="primary" onClick={handleConfirmOrder}>
          确认订单
        </Button>
      </div>
    </div>
  );
  
  // 渲染支付页面
  const renderPayment = () => (
    <div>
      <Card style={{ textAlign: 'center', padding: '30px' }}>
        <h2 style={{ marginBottom: 20 }}>订单确认成功</h2>
        <p style={{ fontSize: 16, marginBottom: 30 }}>请选择支付方式完成订单</p>
        
        <TotalPrice style={{ textAlign: 'center', marginBottom: 30 }}>
          支付金额: ¥{orderDetails.totalPrice}
        </TotalPrice>
        
        <Button 
          type="primary" 
          size="large" 
          onClick={handleSubmitOrder} 
          loading={submitting}
          style={{ width: 200 }}
        >
          立即支付
        </Button>
      </Card>
    </div>
  );
  
  return (
    <MainLayout>
      <PageContainer className="container">
        <Card>
          <StepsContainer>
            <Steps current={currentStep}>
              <Step title="填写信息" description="预订信息和联系方式" />
              <Step title="确认订单" description="确认订单信息" />
              <Step title="完成支付" description="选择支付方式" />
            </Steps>
          </StepsContainer>
          
          {loading ? (
            <div style={{ textAlign: 'center', padding: '50px 0' }}>加载中...</div>
          ) : (
            <>
              {currentStep === 0 && renderContactInfoForm()}
              {currentStep === 1 && renderOrderConfirmation()}
              {currentStep === 2 && renderPayment()}
            </>
          )}
        </Card>
      </PageContainer>
    </MainLayout>
  );
};

export default OrderPage; 